<?php 
#!/usr/local/bin/php
error_reporting(E_ALL & ~E_NOTICE);

app_run();

// run api
function app_run($kw='')
{   
    do {
        echo 'input a keyword(q:exit)';
        $kw = stdio_in();
        if (empty($kw)) continue;
        if ($kw != 'q') search_option($kw);
    } while ( $kw != 'q');
}

// search option
// http://www.btytao.com/s/PPPD-340/page/5.html
function search_option($kw, $option='list')
{
    static $page_info = array();
    while ($option != 'reset') {
        $error = false;
        switch ($option) {
            case 'list':
                $page = 1;
                break;
            case 'next':
                if ($page_info['page']['max']>$page+1) {
                    $page += 1;
                } else {
                    $error = true;
                    echo "don't have next page\n";
                }
                break;
            case 'prev':
                if ($page>1) {
                    $page -= 1;
                } else {
                    $error = true;
                    echo "don't have prev page\n";
                }
                break;
            default: // 选择选项
                $item = intval($option);
                if ($item>0 && $item<16) {
                    $link = $page_info['list'][$item-1];
                    $content = btytao_http_detail_api($link['link']);
                    $magnet  = get_detail($content);
                    $fmt_str = $link['title'].'---'.$link['size'].PHP_EOL.$magnet.PHP_EOL;
                    file_put_contents('target.txt', $fmt_str.PHP_EOL, FILE_APPEND);
                    echo "write file:target.txt success 🎉  !!!\n";
                } else {
                    echo "select item error!!!\n";
                }
                $error = true;
                break;
        }
        if (!$error) {
            $page_info = search_kw($kw, $page);
            echo '📜 curent:'.$page.' all:'.$page_info['page']['max'].PHP_EOL;
            $error = false;
        }
        echo 'option(reset,list,next,prev or number 1~15)';
        $option = stdio_in();
    }
}

function search_kw($kw, $page=1)
{
    echo "search btytao :".$kw."\n";
    $index = 1;
    $html = btytao_http_api($kw, $page);
    $list = get_media_list($html);

    if (count($list) > 1) {
        foreach ($list as $info) {
            echo sprintf("🚩 %02d - %s \n", $index++, $info['title']);
            echo $info['size'].' - '.$info['create']."\n\n";
        }
    } else {
        echo PHP_EOL;
        echo '----------- no result -----------'.PHP_EOL;
        echo PHP_EOL;
    }
    $page = http_page_info($html);
    return array('list'=>$list, 'page'=>$page);
}

// http_page_info();
// html page number info
function http_page_info($html='')
{
    $html = str_replace(PHP_EOL, '', $html);
    $pattern = '/<ul class="pagination.*">(.*)<\/ul>/Ui';
    preg_match_all($pattern, $html, $matches);
    if (count($matches)>1) {
        $pattern = '/<li.*>(.*)<\/li>/Ui';
        preg_match_all($pattern, $matches[1][0], $m);

        // 取最大的页码
        foreach ($m[1] as $value) {
            $num = intval(strip_tags($value));
            if ($num >= $page_info['max']) {
                $page_info['max'] = $num;
            }
        }
    }

    if (empty($page_info)) {
        $page_info = array('max'=>'1');
    }
    return $page_info;
}


function stdio_in()
{
    fwrite(STDOUT,"👉  ");
    $arg = trim(fgets(STDIN));
    return $arg;
}

// get media_list content
function get_media_list($subject)
{
    $info_list = array();
    $subject = str_replace(PHP_EOL, '', $subject);
    $pattern = '/<ul class="media-list media-list-set">(.*?)<\/ul>/i';
    preg_match_all($pattern, $subject, $matches);

    foreach ($matches[0] as $value) {
        $info = get_media($value);
        if (empty($info)) continue;
        $info_list[] = $info;
    }
    return $info_list;
}

// get media
function get_media($subject) 
{
    $medias  = array();
    $pattern = '/<span.*?>(.*?)<\/span>/i';
    preg_match_all($pattern, $subject, $matches);

    if (strpos($matches[1][0], 'mail') !== false) {
        array_shift($matches[1]);
    }

    preg_match('/<a href="(.*)" title=".*">.*<\/a>/Ui', array_pop($matches[1]), $links);
    $medias['link']   = $links[1];

    $medias['size']   = array_pop($matches[1]);
    $medias['create'] = array_pop($matches[1]);

    preg_match('/<h4>(.*?)<\/h4>/Ui', $subject, $title);
    $medias['title'] = trim(strip_tags($title[1]));
    return $medias;
}

// get media magnet
function get_detail($subject)
{
    $subject = str_replace(PHP_EOL, '', $subject);
    $pattern = '/<a href="magnet:.*?">(.*?)<\/a>/i';
    preg_match($pattern, $subject, $matches);
    return $matches[1];
}

// get html
function btytao_http_api($kw, $page=1)
{
    // http://www.btytao.com/s/PPPD-340/page/5.html
    $kw = urlencode($kw);
    if ($page > 1)
        $api = 'http://www.btytao.com/s/'.$kw.'/page/'.$page.'.html';
    else
        $api = 'http://www.btytao.com/s.html?kw='.$kw;

    return my_curl($api);
}

// get detail html
function btytao_http_detail_api($uri='')
{
    $api = 'http://www.btytao.com'.$uri;
    return my_curl($api);
}

// curl
function my_curl($url)
{
    // create a new cURL resource
    $ch = curl_init();

    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置为不自动输出结果
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // grab URL and pass it to the browser
    $result = curl_exec($ch);

    // close cURL resource, and free up system resources
    curl_close($ch);

    return $result;
}



